package com.zyw.security.shiro.web.filter;

import org.apache.shiro.subject.Subject;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 用户访问拦截器，扩展 userFilter
 *
 * @author zhangyw
 * @date 2018/1/11 11:42
 */
public class UserAccessFilter extends BasicAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject;
        if (isLoginRequest(request, response)) {
            subject = getSubject(request, response);
            if (subject.isAuthenticated()) {// 已经登录过，进入首页
                try {
                    saveRequestAndRedirectToSuccess(request, response);
                } catch (Exception e) {
                    log.error("has auth and login redirect to index error {}", e);
                }
                return true;
            } else {
                return true;
            }
        } else {
            subject = getSubject(request, response);
            // If principal is not null, then the user is known and should be allowed access.
            return subject.getPrincipal() != null;
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        saveRequestAndRedirectToLogin(request, response);
        return false;
    }
}
